# -*-coding:utf-8 -*-
#
# Created on 2019/5/13, by felix
#

from rest_framework import serializers

from .models import TemplateInfo


# 200 外键+choice
class TemplateInfoSerializer(serializers.ModelSerializer):
    # 200 验证字段，必须验证为require=True, null=True, blank=True的字段, post的时候
    def validate_price(self, price):
        if price < 0:
            raise serializers.ValidationError("price必须为正整数")
        return price

    # 210 choice, 正序列化 get
    # 表的字段名 = serializers.SerializerMethodField()
    template_type = serializers.SerializerMethodField()

    # def get_字段名(self, obj):
    def get_template_type(self, obj):
        # return obj.get_字段名_display()
        return obj.get_template_type_display()

    # 220 外键, 正序列化 get
    # 自定义的名称 = serializers.要显示的关联表的某字段类型(source='关联的字段.要显示的关联表的某字段')
    # command_name = serializers.CharField(source='command.name')   # 没有required，反序列化的时候，会提示该字段
    command_name = serializers.CharField(source='command.name', required=False)
    command_desc = serializers.CharField(source='command.desc', required=False)

    class Meta:
        model = TemplateInfo
        fields = ('id', 'template_type', 'command_name', 'command_desc', 'price')
        read_only_fields = ('id', 'created_time', 'updated_time')

    # def to_internal_value(self, data):
    #     """反序列化，json转化为serializer"""
    #
    #     return data
    #
    # def to_representation(self, obj):
    #     """serializer转化展示给前端的json"""
    #
    #     return obj
